package com.linshidream.intrachat.simplenio.packet.handler;

import com.linshidream.intrachat.simplenio.packet.context.ConnectionContext;
import com.linshidream.intrachat.simplenio.pipeline.hearbeat.HearbeatState;

import java.io.IOException;

/**
 * Created on 2025/8/17 21:48
 *
 * @author linshidream
 * @version 1.0.0
 * @description
 */

public class ClientPacketHandler implements PacketHandler {

    @Override
    public void channelActive(ConnectionContext ctx) throws IOException {
        System.out.println("客户端已建立连接：" + ctx.channel().getRemoteAddress());
    }

    @Override
    public void channelRead(ConnectionContext ctx, String msg) throws IOException {

        // 下面就是业务处理，我这里简单的只是把消息再次返回，实际场景中根据业务自行开发
        try {
            System.out.println("\n客户端收到服务端消息:" + msg);

            if (HearbeatState.PING.getState().equals(msg)) {
                ctx.writer().send(ctx.codec().encode(HearbeatState.PONG.getState()));
                System.out.println("客户端发送服务端消息:" + HearbeatState.PONG.getState());
            }

            System.out.print("请再次输入你要发送的内容：");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelInactive(ConnectionContext ctx) throws IOException {
        ctx.channel().close();
        System.out.println("客户端已关闭连接");
    }

    @Override
    public void exceptionCaught(ConnectionContext ctx, Throwable e) {
        try {
            System.out.println("客户端连接异常");
            e.printStackTrace();
            ctx.channel().close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
